import "@animxyz/core";
import { XyzTransition } from "@animxyz/react";
import { getDayList } from "@api";
import BackgroundImg from "@assets/bg07.jpg";
import BaseBackground from "@plugin/BaseBackground";
import EnhanceUseNavigate from "@plugin/EnhanceUseNavigate";
import Modal from "@plugin/Modal";
import { GoRegister, IsRegistered, goToMiniPoints } from "@utils";
import React, { Component } from "react";
import styles from "./index.module.scss";

import GetAllRmk from "@assets/get_all_rmk.png";
import GetOneRmk from "@assets/get_one_rmk.png";

import CustomizedYearButton from "@assets/customized_year_button.png";
import GetPointButton from "@assets/get_point.png";
import Mark from "@assets/mark.png";
import RegisterGetPointButton from "@assets/register_get_point.png";
import Tie from "@assets/tie.png";

import GetPointModal from "@assets/get_point_modal.png";
import RegisterModal from "@assets/register_modal.png";
import UnGetPointModal from "@assets/unget_point_modal.png";
import { SendPoint } from "../../../api";
import { navigateToMiniHome } from "../../../utils";
import {
  CampaignIds,
  HaPopupClosed,
  HaPopupOpen,
} from "../../../utils/ha.common";

const marks = {
  Day15: { className: "mark26" },
  Day14: { className: "mark27" },
  Day13: { className: "mark28" },
  Day12: { className: "mark29" },
  Day11: { className: "mark30" },
  Day10: { className: "mark31" },
  Day9: { className: "mark1" },
  Day8: { className: "mark2" },
  Day7: { className: "mark3" },
  Day6: { className: "mark4" },
  Day5: { className: "mark5" },
  Day4: { className: "mark6" },
  Day3: { className: "mark7" },
  Day2: { className: "mark8" },
  Day1: { className: "mark9" },
};

class Index extends Component {
  constructor(props) {
    super(props);

    this.state = {
      registered: IsRegistered(),
      regiserModalStatus: false,
      getPointModalStatus: false,
      unGetPointModalStatus: false,
      awarded: false, //已获得积分
      showFlag: true,
      isAll: false,
      lastDay: undefined,
      markDays: [],
    };
  }

  componentWillUnmount() {
    if (this.state.markDays.length) {
      //缓存本次的结果
      localStorage.setItem(
        "illuminate_days",
        this.state.markDays.map((i) => i.key).join(",")
      );
    }
  }
  componentDidMount() {
    getDayList().then((res) => {
      if (res.state === "ok" && res.data) {
        const list = res.data.list || [];
        const markDays = [];

        if (res.data.last) {
          this.setState({
            lastDay: res.data.last,
          });
        }
        list.map(
          (item) =>
            marks[item] &&
            markDays.push({
              ...marks[item],
              key: item,
            })
        );
        this.setState(
          {
            isAll: list.length >= 15,
            markDays,
          },
          () => {
            this.renderHaPageType(); //记录一下数据， 主要是缓存是否已经集齐
            window._ha("send", "action", "cny_activity3_collectcouppage_view", {
              campaign_id: CampaignIds.activity3,
              page_type: this.renderHaPageType(),
            });
          }
        );
      }
    });
  }

  renderHaPageType() {
    const text = this.state.isAll
      ? IsRegistered()
        ? "member collected"
        : "not member collected"
      : "not all collected";

    sessionStorage.setItem("activity3_page_type", text);
    return text;
  }

  handlerRegiser = () => {
    this.setState({ regiserModalStatus: true });
    window._ha(
      "send",
      "action",
      "cny_activity3_collectcouppage_register_click",
      {
        campaign_id: CampaignIds.activity3,
        page_type: "not member collected",
      }
    );
  };
  closeModal = (type) => {
    this.setState({
      regiserModalStatus: false,
      getPointModalStatus: false,
      unGetPointModalStatus: false,
    });

    //关闭积分弹窗
    if (type && type === "yes") {
      // 已领取积分弹窗：PointsReceivedPopupWindow
      HaPopupClosed(
        "PointsReceivedPopupWindow",
        "cny_activity3_popupwindow_close",
        CampaignIds.activity3
      );
    }

    if (type && type === "no") {
      // 非会员_积分弹窗：NotMember_PointsPopupWindow
      // 会员_积分弹窗：Member_PointsPopupWindow
      HaPopupClosed(
        IsRegistered()
          ? "Member_PointsPopupWindow"
          : "NotMember_PointsPopupWindow",
        "cny_activity3_popupwindow_close",
        CampaignIds.activity3
      );
    }
  };

  goRegiser = () => {
    GoRegister(
      `/pages/userPackage/FY2324_CNY_calendar_Register?fromPage=${encodeURIComponent(
        window.location.href
      )}`
    );

    window._ha(
      "send",
      "action",
      "cny_activity3_notmember_pointspopupwindow_register_click",
      {
        campaign_id: CampaignIds.activity3,
      }
    );
  };

  handlerGetPoint = async () => {
    const res = await SendPoint(); //发放积分。
    if (!res.data) {
      // ?发放失败， 说明已经领取了
      this.setState({
        awarded: true,
        getPointModalStatus: true,
      });

      window._ha(
        "send",
        "action",
        "cny_activity3_pointsreceivedpopupwindow_gotovideo_click",
        {
          campaign_id: CampaignIds.activity3,
        }
      );

      HaPopupOpen(
        "PointsReceivedPopupWindow",
        "cny_activity3_popupwindow_open",
        CampaignIds.activity3
      );
    } else {
      // ?针对未领取的情况
      this.setState({
        awarded: false,
        unGetPointModalStatus: true,
      });

      HaPopupOpen(
        IsRegistered()
          ? "Member_PointsPopupWindow"
          : "NotMember_PointsPopupWindow",
        "cny_activity3_popupwindow_open",
        CampaignIds.activity3
      );
    }

    window._ha(
      "send",
      "action",
      "cny_activity3_collectcouppage_receivepoints_click",
      {
        campaign_id: CampaignIds.activity3,
        page_type: "member collected",
      }
    );
  };

  //跳转查看积分
  viewPoints = () => {
    goToMiniPoints();
    window._ha(
      "send",
      "action",
      "cny_activity3_member_pointspopupwindow_gotocheck_click",
      {
        campaign_id: CampaignIds.activity3,
      }
    );
  };

  handlerCustomized = () => {
    navigateToMiniHome(
      "/pages/userPackage/FY2324CNYBeSpoke?scene=CNYCalendar",
      () => {
        this.props.navigate("/");
      }
    );

    window._ha(
      "send",
      "action",
      "cny_activity3_collectcouppage_gotovideo_click",
      {
        campaign_id: CampaignIds.activity3,
        page_type: this.renderHaPageType(),
      }
    );
  };

  render() {
    const {
      showFlag,
      isAll,
      markDays,
      registered,
      regiserModalStatus,
      getPointModalStatus,
      unGetPointModalStatus,
      lastDay,
    } = this.state;
    return (
      <>
        <BaseBackground
          backgroundImage={BackgroundImg}
          showFlag={showFlag}
          bigLogo={true}
        >
          <div className={styles.sign_box}>
            {isAll ? (
              <img src={GetAllRmk} className={styles.get_all_rmk} alt="" />
            ) : (
              <img src={GetOneRmk} className={styles.get_one_rmk} alt="" />
            )}
          </div>

          <div className={styles.tie_box}>
            <img className={styles.tie} src={Tie} alt="" />

            {markDays.map((item, index) => (
              <XyzTransition
                key={item.key}
                appear
                appearVisible
                xyz={lastDay === item.key ? `fade duration-10 big-100%` : ""}
              >
                <img
                  data-day={item.key}
                  className={`${styles.mark} ${styles[item.className]}`}
                  src={Mark}
                  alt=""
                />
              </XyzTransition>
            ))}
          </div>

          <div
            className={`${isAll ? "" : styles.option_group_one} ${
              styles.option_group
            }`}
          >
            {isAll ? (
              <>
                {registered ? (
                  <img
                    src={GetPointButton}
                    onClick={this.handlerGetPoint}
                    className={styles.get_point_button}
                    alt=""
                  />
                ) : (
                  <img
                    onClick={this.handlerRegiser}
                    src={RegisterGetPointButton}
                    className={styles.register_get_point_button}
                    alt=""
                  />
                )}
              </>
            ) : (
              ""
            )}
            <img
              onClick={this.handlerCustomized}
              src={CustomizedYearButton}
              className={styles.customized_year_button}
              alt=""
            />
          </div>
        </BaseBackground>

        {regiserModalStatus && (
          <Modal>
            <div className={styles.modal_conetnt}>
              <img
                src={RegisterModal}
                className={styles.register_modal_img}
                alt=""
              />
              <div
                onClick={this.closeModal}
                className={styles.modal_action_close}
              ></div>
              <div
                onClick={this.goRegiser}
                className={styles.modal_action_button}
              ></div>
            </div>
          </Modal>
        )}

        {getPointModalStatus && (
          <Modal>
            <div className={styles.modal_conetnt}>
              <img
                src={GetPointModal}
                className={styles.get_point_modal_img}
                alt=""
              />
              <div
                onClick={() => this.closeModal("yes")}
                className={styles.modal_action_close}
              ></div>
              <div
                onClick={this.handlerCustomized}
                className={styles.modal_action_button}
              ></div>
            </div>
          </Modal>
        )}

        {unGetPointModalStatus && (
          <Modal>
            <div className={styles.modal_conetnt}>
              <img
                src={UnGetPointModal}
                className={styles.register_modal_img}
                alt=""
              />
              <div
                onClick={() => this.closeModal("no")}
                className={styles.modal_action_close}
              ></div>
              <div
                onClick={this.viewPoints}
                className={styles.modal_action_button}
              ></div>
            </div>
          </Modal>
        )}
      </>
    );
  }
}

export default EnhanceUseNavigate(Index);
